package com.cs342.uwosh.cloudycontacts.tasks.network;

import java.io.InputStream;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.ByteArrayEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;
import org.json.*;

import android.graphics.Typeface;
import android.os.AsyncTask;
import android.util.Log;
import android.widget.TextView;
import android.widget.Toast;

import com.cs342.uwosh.cloudycontacts.Category;
import com.cs342.uwosh.cloudycontacts.Contact;
import com.cs342.uwosh.cloudycontacts.DisplayFromJson;
import com.cs342.uwosh.cloudycontacts.MainActivity;
import com.cs342.uwosh.cloudycontacts.RestClient;
import com.cs342.uwosh.cloudycontacts.SqlConnect;
import com.cs342.uwosh.cloudycontacts.tasks.db.AddContactTask;
import com.cs342.uwosh.cloudycontacts.tasks.db.CreateCategoryTask;
import com.cs342.uwosh.cloudycontacts.tasks.db.GetAllCategoryNamesTask;
import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;

public class GetFromJsonTask extends AsyncTask<String, String, Object>
{
	public int iLanguage = 0;
	Typeface arabicFont = null;
	int TIMEOUT_MILLISEC = 10000; // = 10 seconds
	
	
	@Override
	protected Object doInBackground(String... params) {
		String returnThis = "";
		try
		{
			JSONObject json = new JSONObject();
			json.put("user_name", params[0]);
			json.put("password", params[1]);
			
			HttpParams httpParams = new BasicHttpParams();
			HttpConnectionParams.setConnectionTimeout(httpParams,
					TIMEOUT_MILLISEC);
			HttpConnectionParams.setSoTimeout(httpParams, TIMEOUT_MILLISEC);
			HttpClient client = new DefaultHttpClient(httpParams);
			
			//String url = "http://10.0.2.2:8080/sample1/webservice2.php?json={\"UserName\":1,\"FullName\":2}";
			String url = "http://softeng.cs.uwosh.edu/students/kiserj66/Web/webservice.php";

			HttpPost request = new HttpPost(url);
			request.setEntity(new ByteArrayEntity(json.toString().getBytes(
					"UTF8")));
			request.setHeader("json", json.toString());
			HttpResponse response = client.execute(request);
			HttpEntity entity = response.getEntity();
			// If the response does not enclose an entity, there is no need
			if (entity != null) {
				InputStream instream = entity.getContent();
				String result = RestClient.convertStreamToString(instream);
				Log.i("Read from server", result);
				returnThis = result;
			}
		}
		catch (Throwable t)
		{
			returnThis = "Request failed: " + t.toString();
		}
		return returnThis;
	}
	
	@Override
	protected void onPostExecute(Object result)
	{
		JsonObject appData = (JsonObject) new JsonParser().parse((String) result);
		SqlConnect db = MainActivity.db;
		db.dropTables();
		populateContactsTable(appData);
		populateCategoriesTable(appData);
		new GetAllCategoryNamesTask().execute();
	}
	
	private void populateContactsTable(JsonObject jObj)
	{
		JsonElement jEl = jObj.get("contacts");
		JsonArray jAr = jEl.getAsJsonArray();
		
		for (int i = 0; i < jAr.size(); i++)
		{
			JsonObject jObj2 = (JsonObject) jAr.get(i);
			new AddContactTask().execute(
					new Contact(
							jObj2.get("name").getAsString(),
							jObj2.get("address").getAsString(),
							jObj2.get("cell_number").getAsString(),
							jObj2.get("alt_number").getAsString(),
							jObj2.get("email").getAsString(),
							jObj2.get("comments").getAsString(),
							Integer.parseInt(jObj2.get("category").getAsString()),
							jObj2.get("ts").getAsString()
							)
					); 
		}
	}
	
	private void populateCategoriesTable(JsonObject jObj)
	{
		JsonElement jEl = jObj.get("categories");
		JsonArray jAr = jEl.getAsJsonArray();
		
		for (int i = 0; i < jAr.size(); i++)
		{
			JsonObject jObj2 = (JsonObject) jAr.get(i);
			new CreateCategoryTask().execute(
					new Category(
							Integer.parseInt(jObj2.get("cid").getAsString()),
							jObj2.get("category_name").getAsString(),
							jObj2.get("ts").getAsString()
							)
					);
		}
	}
	

}
